package com.tripspins.app.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;

import com.tripspins.app.R;
import com.tripspins.app.bo.Attachment;
import com.tripspins.app.bo.Pin;
import com.tripspins.app.exception.NoConnectionException;
import com.tripspins.app.exception.OfflineModeException;
import com.tripspins.app.helper.SocialHelper;
import com.tripspins.app.interfaces.OnTaskCompleted;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.ProfilePictureView;

import java.util.ArrayList;

import ch.boye.httpclientandroidlib.client.cache.Resource;

/**
 * Created by João.Rutkoski on 15/10/13.
 */
public class AttachmentListAdapter extends BaseAdapter {

    private final Activity activity;
    private ArrayList<Attachment> attachments;
    private static LayoutInflater inflater = null;
    private UiLifecycleHelper uiHelper;
    private Pin pin;
    private long idTrip;
    AttachmentListAdapter attachmentListAdapter;
    public AttachmentListAdapter(Activity a, Pin pin, long idTrip, UiLifecycleHelper uiHelper)
    {
        this.attachments = pin.getAttachments();
        activity = a;
        this.pin = pin;
        this.idTrip = idTrip;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.uiHelper = uiHelper;
        attachmentListAdapter = this;
    }
    public AttachmentListAdapter(Activity a, ArrayList<Attachment> attachments)
    {
        this.attachments = attachments;
        activity = a;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        attachmentListAdapter = this;
    }

    private static class ViewHolder
    {
        public Attachment attachment;
        public ImageButton imgThumbnail;
        public ProfilePictureView fbContactPiture;
    }

    @Override
    public int getCount() {
        return attachments.size();
    }

    @Override
    public Object getItem(int i) {
        return attachments.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        final int index = i;
        if(view == null) {
            v = inflater.inflate(R.layout.new_pin_attachment_row, null);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.imgThumbnail = (ImageButton)v.findViewById(R.id.new_pin_img_att);
            viewHolder.fbContactPiture = (ProfilePictureView)v.findViewById(R.id.new_pin_att_fb_picture);
            viewHolder.attachment = (Attachment)getItem(i);
            v.setTag(viewHolder);
        }
        v.setClickable(true);
        v.setFocusable(true);
        ViewHolder vHolder = (ViewHolder)v.getTag();

        new AsyncTask<ViewHolder, Void, Bitmap>(){
            private ViewHolder holder;
            @Override
            protected Bitmap doInBackground(ViewHolder... params) {
                holder = params[0];

                switch (attachments.get(index).getFileType())
                {
                    case   AUDIO:
                        Resources imgResource = activity.getResources();
                        int imgId = R.drawable.ic_action_mic_b;
                        return BitmapFactory.decodeResource(imgResource,imgId);

                    case CONTACT:
                        return null;
                    case IMAGE:
                        try{
                            return BitmapFactory.decodeFile(attachments.get(index).getThumbnailPath());
                        }catch(OutOfMemoryError error)
                        {
                            try{
                                System.gc();
                                return  BitmapFactory.decodeFile(attachments.get(index).getThumbnailPath());
                            }
                            catch(OutOfMemoryError error2){}
                        }
                        break;
                    case VIDEO:
                        try{
                            return BitmapFactory.decodeFile(attachments.get(index).getThumbnailPath());
                        }catch(OutOfMemoryError error)
                        {
                            try{
                                System.gc();
                                return  BitmapFactory.decodeFile(attachments.get(index).getThumbnailPath());
                            }
                            catch(OutOfMemoryError error2){}
                        }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);
                if (bitmap == null && attachments.get(index).getContact() != null){
                    holder.fbContactPiture.setProfileId(attachments.get(index).getContact().getContactIdOnSource());
                    holder.fbContactPiture.setVisibility(View.VISIBLE);
                    holder.imgThumbnail.setVisibility(View.INVISIBLE);
                }
                else{holder.imgThumbnail.setImageBitmap(bitmap);}
            }
        }.execute(vHolder);


        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DeleteItemDialog dialog = new DeleteItemDialog();
                dialog.setParamenter(attachmentListAdapter);
                dialog.show(activity.getFragmentManager(), String.valueOf(index));

            }
        });

        v.setOnLongClickListener( new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                ViewHolder vHolder = (ViewHolder)view.getTag();
                SocialHelper socialHelper = new SocialHelper();
                try {
                    socialHelper.shareOnFacebook(idTrip, pin.getId(), vHolder.attachment, ((OnTaskCompleted)activity));
                } catch (NoConnectionException e) {
                    e.printStackTrace();
                } catch (OfflineModeException e) {
                    e.printStackTrace();
                }
                return true;
            }
        });

        return v;
    }
    private void deleteAttachment(int index, int gridIndex) {
        if(index == 0)
        {
            attachments.remove(gridIndex);
            notifyDataSetChanged();
        }
    }

    public static class DeleteItemDialog extends DialogFragment {

        static AttachmentListAdapter attachmentListAdapter;

        public static void setParamenter(AttachmentListAdapter a){
            attachmentListAdapter = a;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.dialog_delete_attachment);
            final Bundle savedInstance = savedInstanceState;
            final int gridIndex = Integer.parseInt(getTag());
            builder.setItems(R.array.dialog_delete_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int index) {
                    attachmentListAdapter.deleteAttachment(index, gridIndex);
                }
            });
            return builder.create();
        }
    }


}
